package com.xyy.saas.payment.callback.core.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.xyy.elasticjob.client.annotation.ElasticJobConf;
import com.xyy.saas.payment.adpater.RouteManager;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.dao.model.PayResultOrder;
import com.xyy.saas.payment.dao.model.RefundOrder;
import com.xyy.saas.payment.merchant.core.dto.QueryChannelClearDto;
import com.xyy.saas.payment.merchant.core.dto.QueryChannelClearVo;
import com.xyy.saas.payment.payment.core.dto.RefundDto;
import com.xyy.saas.payment.payment.core.service.PaymentService;
import com.xyy.saas.payment.payment.core.service.RefundOrderService;
import com.xyy.saas.payment.service.PayResultOrderService;
import com.xyy.saas.payment.util.DateUtil;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;

/**
 * 发送延迟退款单
 */
@Slf4j
@ElasticJobConf(name = "com.xyy.saas.payment.callback.core.job.SendDelayRefundOrderJob", cron = "0 0 9-21 * * ?")
public class SendDelayRefundOrderJob implements SimpleJob {
    @Resource
    private RefundOrderService refundOrderService;
    @Resource
    private PayResultOrderService payResultOrderService;
    @Resource
    private RouteManager routeManager;
    @Resource
    private PaymentService paymentService;

    @Override
    public void execute(ShardingContext shardingContext) {
        long startTime = System.currentTimeMillis();
        log.info("SendDelayRefundOrderJob#execute start.");

        int pageOffset = 0;
        int pageSize = 50;

        while(true) {
            List<RefundOrder> items = refundOrderService.selectListByStatusAndPayChannel(StringUtils.EMPTY, RefundOrder.STATUS_DELAY, pageOffset, pageSize);

            if(CollectionUtils.isEmpty(items)) {
                break;
            }

            for(RefundOrder item : items) {
                try {
                    PayResultOrder resultOrder = payResultOrderService.selectByPayNoAndChannel(item.getPayNo(), item.getChannel());
                    String payDate = DateUtil.format(resultOrder.getCtime(), DateUtil.DATEFORMATDAY_02);

                    QueryChannelClearVo queryChannelClearVo = routeManager.queryChannelClear(QueryChannelClearDto.builder().
                            businessIdType(resultOrder.getBusinessOrderType()).
                            accountId(resultOrder.getReceiveId()).
                            startDate(payDate).
                            endDate(payDate).
                            build());

                    // 未清分
                    if(!queryChannelClearVo.isClearFinish()) {
                        continue;
                    }

                    // 已清分，发起退款
                    RefundDto refundDto = new RefundDto();
                    refundDto.setAmount(item.getAmount());
                    refundDto.setBusinessRefundNo(item.getBusinessRefundNo());
                    refundDto.setBusinessType(resultOrder.getBusinessType());
                    refundDto.setBusinessOrderType(resultOrder.getBusinessOrderType());
                    refundDto.setCallbackUrl(item.getCallbackAddress());
                    refundDto.setChannel(item.getChannel());
                    refundDto.setDescription("支付平台订单退款");
                    refundDto.setPayNo(item.getPayNo());
                    paymentService.refund(refundDto);
                }
                catch(Exception ex) {
                    log.error(ex.getMessage() + ", refundOrder=" + JSONUtils.toJSON(item), ex);
                }
            }

            if(items.size() < pageSize) {
                break;
            }

            pageOffset += pageSize;
        }

        log.info("SendDelayRefundOrderJob#execute end. cost={}", (System.currentTimeMillis() - startTime));
    }
}
